package com.example.mvvmtest.test;

import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;

import com.example.mvvmtest.R;
import com.example.mvvmtest.model.bean.TestBean;

import java.util.HashMap;
import java.util.List;

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyHolder> {
    private List<TestBean> mList;
    private int layoutId;

    public MyAdapter(int layoutId, List<TestBean> data) {
        this.layoutId = layoutId;
        this.mList = data;
    }

    @NonNull
    @Override
    public MyHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(layoutId, viewGroup, false);
        return new MyHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull MyHolder myHolder, int position) {
        final TestBean item = mList.get(position);
        myHolder.itemView.setTag(position);
        myHolder.setText(R.id.tv_title, item.getTitle());
        myHolder.setText(R.id.tv_date, item.getDate());
        myHolder.setText(R.id.tv_count, item.getCount() + "");
        myHolder.setSwitch(R.id.switch_1, item.isOut());
    }


    @Override
    public int getItemCount() {
        return mList.size();
    }

    static class MyHolder extends RecyclerView.ViewHolder {
        HashMap<Integer, View> mViews = new HashMap<>();

        public MyHolder(@NonNull View itemView) {
            super(itemView);
        }

        /**
         * 获取控件的方法
         */
        public <T> T getView(Integer viewId) {
            //根据保存变量的类型 强转为该类型
            View view = mViews.get(viewId);
            if (view == null) {
                view = itemView.findViewById(viewId);
                //缓存
                mViews.put(viewId, view);
            }
            return (T) view;
        }

        /**
         * 传入文本控件id和设置的文本值，设置文本
         */
        public MyHolder setText(Integer viewId, String value) {
            TextView textView = getView(viewId);
            if (textView != null) {
                textView.setText(value);
            }
            return this;
        }

        /**
         * 传入图片控件id和资源id，设置图片
         */
        public MyHolder setImageResource(Integer viewId, Integer resId) {
            ImageView imageView = getView(viewId);
            if (imageView != null) {
                imageView.setImageResource(resId);
            }
            return this;
        }

        /**
         * 传入图片控件id和资源id，设置图片
         */
        public MyHolder setSwitch(Integer viewId, boolean value) {
            Switch switchView = getView(viewId);
            if (switchView != null) {
                switchView.setChecked(value);
            }
            return this;
        }
    }
}
